from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
import random
from rest_framework import serializers
from celery_tasks.sms import tasks


# 接收短信验证码
class SMSCodeView(APIView):
    # 接收参数为手机号,不涉及关系型数据库,不需要反序列化
    # 当前输出对象为字典,故不需要序列化
    def get(self, request, mobile):
        # 获得redis的连接
        redis_cli = get_redis_connection('verify_code')
        # 验证60s之内是否已经发送过验证码
        sms_flag = redis_cli.get('sms_flag_' + mobile)
        if sms_flag:
            # 利用drf抛异常
            raise serializers.ValidationError('请稍后再试!')
        sms_code = str(random.randint(100000, 999999))
        # redis_cli.setex('sms_code_'+mobile, 300, sms_code)
        # redis_cli.setex('sms_flag_'+mobile, 60, 1)
        # 优化redis交互，减少通信的次数，管道pipeline
        redis_pl = redis_cli.pipeline()
        # 拼接
        redis_pl.setex('sms_code_' + mobile, 300, sms_code)
        redis_pl.setex('sms_flag_' + mobile, 60, 1)
        # 执行
        redis_pl.execute()
        tasks.send_sms.delay(mobile, sms_code, 5, 1)
        return Response({'send_status': 'OK'})
